package com.TT.controller;

import com.TT.common.REST.RESTResponse;
import com.TT.common.REST.ResCode;
import com.TT.common.unifiedLogPrint.RecordLog;
import com.TT.common.unifiedLogPrint.dictionary.Level;
import com.TT.common.utils.DataTablePageUtil;
import com.TT.domain.mysql.User;
import com.TT.domain.vo.Ids;
import com.TT.service.mysql.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 苏文广 on 2018/11/26
 * 用户功能控制器
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController {
    @Resource
    private UserService userService;

    /**
     * 员工注册接口
     *
     * @param user          员工
     * @param bindingResult 校验结果类
     *
     * @return RESTResponse rest响应层
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public RESTResponse register(@RequestBody @Validated User user, BindingResult bindingResult) {
        String validate = this.validate(bindingResult);
        if (validate != null) {
            return RESTResponse.msg_Fail(validate);
        }
        //注册业务
        try {
            userService.register(user);
            return RESTResponse.msg_Success(user.toString());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return RESTResponse.simple_fail();
        }
    }

    /**
     * 登陆
     *
     * @param user          带用户名和密码的员工类
     * @param bindingResult 校验结果
     *
     * @return RESTResponse rest响应层
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @RecordLog(oprationName = "登陆", level = Level.Essential_Level)
    public RESTResponse login(@RequestBody @Validated User user, BindingResult bindingResult, HttpSession session) {
        String validate = this.validate(bindingResult);
        if (validate != null) {
            return RESTResponse.msg_Fail(validate);
        }
        try {
            User login = userService.login(user);
            //设置session
            session.setAttribute("token", login);
            return RESTResponse.simple_success();
        } catch (Exception e) {
            tryLog(e);
            return RESTResponse.simple_fail();
        }
    }

    /**
     * 更新个人信息
     *
     * @param user    更新的用户信息
     * @param session 用户会话
     *
     * @return RESTResponse
     */
    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    @RecordLog(oprationName = "更新个人信息", level = Level.INFO_Level)
    public RESTResponse updateInfo(@RequestBody User user, HttpSession session) {
        try {
            User token = (User) session.getAttribute("token");
            if (!ObjectUtils.anyNotNull(token)) {
                return RESTResponse.msg_Fail("会话过期，请重新登陆");
            }
            //设置属性
            token.setCurrentResidence(user.getCurrentResidence());
            token.setJobTitle(user.getJobTitle());
            token.setName(user.getName());
            token.setPhone(user.getPhone());
            token.setShared(user.getShared());
            userService.updateInfo(token);
            session.setAttribute("token", token);
            return RESTResponse.msg_Success("更新成功");
        } catch (Exception e) {
            tryLog(e);
            return RESTResponse.simple_fail();
        }
    }

    /**
     * 查询个人信息
     *
     * @param session 用户会话
     *
     * @return RESTResponse<User>
     */
    @RequestMapping(value = "/queryInfo", method = RequestMethod.GET)
    @RecordLog(oprationName = "查询个人信息", level = Level.INFO_Level)
    public RESTResponse<User> queryInfo(HttpSession session) {
        try {
            User token = (User) session.getAttribute("token");
            if (ObjectUtils.anyNotNull(token)) {
                return new RESTResponse<>(ResCode.Simple_SUCESS, token);
            } else {
                return new RESTResponse<>(ResCode.Msg_FAIL.getCode(), "会话过期，请重新登陆", null);
            }
        } catch (Exception e) {
            tryLog(e);
            return new RESTResponse<>(ResCode.Simple_FAIL, null);
        }
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public DataTablePageUtil list(HttpServletRequest request) {

        //使用DataTables的属性接收分页数据
        DataTablePageUtil<User> dataTable = new DataTablePageUtil<User>(request);
        //开始分页：PageHelper会处理接下来的第一个查询
        PageHelper.startPage(dataTable.getPage_num(), dataTable.getPage_size(), dataTable.getOrderBy());
        ArrayList<User> userListOrderByUserName = userService.getUserList();
        PageInfo<User> pageInfo = new PageInfo<>(userListOrderByUserName);
        //封装数据给DataTables
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        return dataTable;
    }

    @RequestMapping(value = "/updateByAdmin", method = RequestMethod.POST)
    public RESTResponse updateByAdmin(@RequestBody User user) {
        try {
            userService.updateByAdmin(user);
            return RESTResponse.simple_success();
        } catch (Exception e) {
            tryLog(e);
            return RESTResponse.simple_fail();
        }
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RESTResponse deleteByUserId(@PathVariable long id) {
        try {
            userService.deleteByUserId(id);
            return RESTResponse.simple_success();
        } catch (Exception e) {
            tryLog(e);
            return RESTResponse.simple_fail();
        }
    }

    @RequestMapping("/multiDelete")
    public RESTResponse multiDelete(@RequestBody Ids ids) {
        try {
            List ids1 = ids.getIds();

            for (Object integer : ids1) {
                userService.deleteByUserId((Integer) integer);
            }
            return RESTResponse.simple_success();
        } catch (Exception e) {
            tryLog(e);
            return RESTResponse.simple_fail();
        }
    }


}
